import React from 'react';
import _ from 'lodash';
import styled from 'styled-components';
import dayjs from 'dayjs';
import { NumberView } from '@/components/BaseTable';
import { Tooltip } from 'antd';

const TableCell = styled.div`
  display: flex;
  align-items: center;
  text-align: center;
  justify-content: center;
  flex-direction: column;
`;

// 签约与回款
const signAndReturn = [
  'totalValue', // 总货值
  'accumulativeSold', // 累计已售
  'accumulativeReturn', // 累计已回款
  'signNotReturn', // 已签未回
  'notSignNotReturn', // 未签未回
  'signReturnRate', // 累计签约回款率
];
// 年度数据
const yearData = [
  'yearEarlyReceivable', // 年初应收账款
  'yearSign', // 年度签约
  'annualActualIncrementalReturn', // 年度实际数-增量回款
  'annualActualStoreReturn', // 年度实际数-存量回款
  'annualCalculateIncrementalReturn', // 年度测算数-增量回款
  'annualCalculateStoreReturn', // 年度测算数-存量回款
  'annualAdjustIncrementalReturn', // 年度调整数-增量回款
  'annualAdjustStoreReturn', // 年度调整数-存量回款
  'yearSignNotReturn', // 年度已签未回回款数
  'yearEarlyRefund', // 年初应退
  'annualTotalIncrementalReturn', // 年度回款合计-增量回款
  'annualTotalStoreReturn', // 年度回款合计-存量回款
  'annualTotalReturnTotal', // 年度回款合计-回款合计
  'annualTotalYearEndReceivable', // 年度回款合计-年末应收账款
];
// 实际月
const actualMonth = [
  'monthEarlyReceivable', // 月初应收账款
  'monthSign', // 月度签约
  'monthlyTotalIncrementalReturn', // 月度回款合计-增量回款
  'monthlyTotalStoreReturn', // 月度回款合计-存量回款
  'monthlyTotalReturnTotal', // 月度回款合计-回款合计
  'signReturnRate', // 累计签约回款率
  'annualOverallReturnRate', // 年度综合回款率
];
// 当前月
const currentMonth = [
  'monthEarlyReceivable', // 月初应收账款
  'monthSign', // 月度签约
  'monthlyActualIncrementalReturn', // 月度实际数-增量回款
  'monthlyActualStoreReturn', // 月度实际数-存量回款
  'monthlyCalculateIncrementalReturn', // 月度测算数-增量回款
  'monthlyCalculateStoreReturn', // 月度测算数-存量回款
  'monthlyAdjustIncrementalReturn', // 月度调整数-增量回款
  'monthlyAdjustStoreReturn', // 月度调整数-存量回款
  'monthSignNotReturn', // 月度已签未回回款数
  'refundable', // 期初应退回款数
  'monthlyTotalIncrementalReturn', // 月度回款合计-增量回款
  'monthlyTotalStoreReturn', // 月度回款合计-存量回款
  'monthlyTotalReturnTotal', // 月度回款合计-回款合计
  'monthlyTotalMonthEndReceivable', // 月度回款合计-月末应收账款
  'signReturnRate', // 累计签约回款率
  'annualOverallReturnRate', // 年度综合回款率
];
// 计划月
const planMonth = [
  'monthEarlyReceivable', // 月初应收账款
  'monthSign', // 月度签约
  'monthlyCalculateIncrementalReturn', // 月度测算数-增量回款
  'monthlyCalculateStoreReturn', // 月度测算数-存量回款
  'monthlyAdjustIncrementalReturn', // 月度调整数-增量回款
  'monthlyAdjustStoreReturn', // 月度调整数-存量回款
  'monthSignNotReturn', // 月度已签未回回款数
  'monthlyTotalIncrementalReturn', // 月度回款合计-增量回款
  'monthlyTotalStoreReturn', // 月度回款合计-存量回款
  'monthlyTotalReturnTotal', // 月度回款合计-回款合计
  'monthlyTotalMonthEndReceivable', // 月度回款合计-月末应收账款
  'signReturnRate', // 累计签约回款率
  'annualOverallReturnRate', // 年度综合回款率
];

export const getExpandedRowKeys = list => {
  const expandedRowKeys = [];
  _.forEach(list, value => {
    expandedRowKeys.push(value.id);
  });
  return expandedRowKeys;
};

export const hasChildren = (list, item) => {
  let result = false;
  list.forEach(value => {
    if (value.pid === item.id) {
      result = true;
    }
  });
  return result;
};

export const buildTree = (list, pid = '0') => {
  const tree = [];
  list.forEach(value => {
    if (value.pid === pid) {
      if (hasChildren(list, value)) {
        value.children = [];
        value.children = buildTree(list, value.id);
      }
      tree.push(value);
    }
  });
  return tree;
};

export const getArrayNumbers = (text, division = 1) => {
  if (!_.isEmpty(text) && text.indexOf('/') > -1) {
    // text.split('/')
    const temp = [];
    _.forEach(text.split('/'), value => {
      temp.push((_.trim(value) * 1) / division);
    });
    text = temp;
  } else {
    text = (text * 1) / division;
  }

  return text;
};

export const getFixedColumns = (currentYear, currentMonths) => {
  let fixedColumns = [
    {
      key: 'name',
      dataKey: 'name',
      width: 300,
      frozen: 'left',
      cellRenderer: ({ rowData }) => (
        <div className="ellipsis">
          <Tooltip placement="topLeft" title={rowData.name}>
            {rowData.name}
          </Tooltip>
        </div>
      ),
    },
    {
      key: 'carryOverTimeStr',
      dataKey: 'carryOverTimeStr',
      align: 'center',
      width: 100,
    },
  ];
  _.forEach(signAndReturn, v => {
    const isPercentage = v === 'signReturnRate';
    fixedColumns.push({
      key: v,
      dataKey: v,
      title: isPercentage ? '（%）' : '金额（万元）',
      align: 'right',
      width: 100,
      dataGetter: ({ rowData }) => {
        let val = 0;
        if (isPercentage) {
          val = `${(rowData.signAndReturn[v] * 100).toFixed(3)}%`;
        } else {
          val = rowData.signAndReturn[v] / 10000;
        }
        return val;
      },
      cellRenderer: data => {
        let val = '';
        if (isPercentage) {
          val = data.cellData;
        } else {
          val = <NumberView {...data} precision={4} />;
        }
        return val;
      },
    });
  });
  // 筛选项里是否有年度合计
  if (_.includes(currentMonths, '14'.toString())) {
    const newYearDataArr = [];
    _.forEach(yearData, v => {
      newYearDataArr.push({
        key: `${currentYear}-${v}`,
        dataKey: `${currentYear}-${v}`,
        title: '金额（万元）',
        align: 'right',
        width: 100,
        dataGetter: ({ rowData }) => [rowData.yearData ? rowData.yearData[v] / 10000 : 0],
        cellRenderer: <NumberView precision={4} />,
      });
    });
    fixedColumns = _.concat(fixedColumns, newYearDataArr);
  }
  // 月份
  for (let i = 1; i <= 12; i += 1) {
    if (_.includes(currentMonths, i.toString())) {
      // 是否是当前时间之前
      const isCurrentTimeBefore = dayjs(`${currentYear}-${i}`).isBefore();
      // 是否是当前时间
      const isCurrentTime = dayjs(`${currentYear}-${i}`).isSame(dayjs().format('YYYY-MM'));
      // 实际月
      if (!isCurrentTime && isCurrentTimeBefore) {
        _.forEach(actualMonth, v => {
          // 是百分比
          const isPercentage = v === 'signReturnRate' || v === 'annualOverallReturnRate';
          fixedColumns.push({
            key: `${currentYear}-${i}-${v}`,
            dataKey: `${currentYear}-${i}-${v}`,
            title: isPercentage ? '（%）' : '金额（万元）',
            align: 'right',
            width: 100,
            dataGetter: ({ rowData }) => {
              let val = 0;
              if (isPercentage) {
                val = rowData.monthDataList[i - 1]
                  ? `${(rowData.monthDataList[i - 1][v] * 100).toFixed(3)}%`
                  : '0.0%';
              } else {
                val = rowData.monthDataList[i - 1] ? rowData.monthDataList[i - 1][v] / 10000 : 0.0;
              }
              return val;
            },
            cellRenderer: data => {
              let val = '';
              if (isPercentage) {
                val = data.cellData;
              } else {
                val = <NumberView {...data} precision={4} />;
              }
              return val;
            },
          });
        });
      }
      // 当前月
      if (isCurrentTime) {
        _.forEach(currentMonth, v => {
          // 是百分比
          const isPercentage = v === 'signReturnRate' || v === 'annualOverallReturnRate';
          fixedColumns.push({
            key: `${currentYear}-${i}-${v}`,
            dataKey: `${currentYear}-${i}-${v}`,
            title: isPercentage ? '（%）' : '金额（万元）',
            align: 'right',
            width: 100,
            dataGetter: ({ rowData }) => {
              let val = 0;
              if (isPercentage) {
                val = rowData.monthDataList[i - 1]
                  ? `${(rowData.monthDataList[i - 1][v] * 100).toFixed(3)}%`
                  : '0.0%';
              } else {
                val = rowData.monthDataList[i - 1] ? rowData.monthDataList[i - 1][v] / 10000 : 0.0;
              }
              return val;
            },
            cellRenderer: data => {
              let val = '';
              if (isPercentage) {
                val = data.cellData;
              } else {
                val = <NumberView {...data} precision={4} />;
              }
              return val;
            },
          });
        });
      }
      // 计划月
      if (!isCurrentTime && !isCurrentTimeBefore) {
        _.forEach(planMonth, v => {
          // 是百分比
          const isPercentage = v === 'signReturnRate' || v === 'annualOverallReturnRate';
          fixedColumns.push({
            key: `${currentYear}-${i}-${v}`,
            dataKey: `${currentYear}-${i}-${v}`,
            title: isPercentage ? '（%）' : '金额（万元）',
            align: 'right',
            width: 100,
            dataGetter: ({ rowData }) => {
              let val = 0;
              if (isPercentage) {
                val = rowData.monthDataList[i - 1]
                  ? `${(rowData.monthDataList[i - 1][v] * 100).toFixed(3)}%`
                  : '0.0%';
              } else {
                val = rowData.monthDataList[i - 1] ? rowData.monthDataList[i - 1][v] / 10000 : 0.0;
              }
              return val;
            },
            cellRenderer: data => {
              let val = '';
              if (isPercentage) {
                val = data.cellData;
              } else {
                val = <NumberView {...data} precision={4} />;
              }
              return val;
            },
          });
        });
      }
    }
  }
  return fixedColumns;
};

export const getTitleTree = (currentYear, currentMonths) => {
  const titleTree = [
    {
      name: '项目/分期/组团/产品类型',
      key: 'id',
      colspan: 1,
      rowspan: 5,
      frozen: 'left',
    },
    {
      name: '结转日期',
      key: 'carryOverTimeStr',
      colspan: 1,
      rowspan: 5,
    },
    {
      name: '签约与回款',
      key: 'allSignReturnMoney',
      rowspan: 2,
      children: [],
    },
    {
      name: '',
      isTabs: true,
      key: 'yearTotalCount',
      children: [],
    },
  ];
  // 签约与回款
  titleTree[2].children = [
    {
      name: (
        <TableCell>
          <div>总货值</div>
          <div>(A)</div>
        </TableCell>
      ),
      key: 'allGoodsValue',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
    {
      name: (
        <TableCell>
          <div>累计已售</div>
          <div>(B=C+D)</div>
        </TableCell>
      ),
      key: 'cumulativeSold',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
    {
      name: (
        <TableCell>
          <div>累计已回款</div>
          <div>(C)</div>
        </TableCell>
      ),
      key: 'cumulativePaymentReceived',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
    {
      name: (
        <TableCell>
          <div>已签未回</div>
          <div>(D)</div>
        </TableCell>
      ),
      key: 'SignedNotBack',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
    {
      name: (
        <TableCell>
          <div>未签未回</div>
          <div>(A-B)</div>
        </TableCell>
      ),
      key: 'notSignedNotBack',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
    {
      name: (
        <TableCell>
          <div>累计签约回款率</div>
          <div>(C/B)</div>
        </TableCell>
      ),
      key: 'accumulativeContractPaymentRateWithoutSigning',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
  ];
  // table header点击的年份
  const columns = [
    {
      name: `${currentYear}年度`,
      key: `${currentYear}Year`,
      hidden: !_.includes(currentMonths, '14'),
      children: [
        {
          name: '年初应收账款',
          key: `${currentYear}-yearEarlyReceivable`,
          colspan: 1,
          rowspan: 2,
        },
        {
          name: '年度签约',
          key: `${currentYear}-yearSign`,
          colspan: 1,
          rowspan: 2,
        },
        {
          name: '年度实际数',
          key: `${currentYear}-annualActual`,
          colspan: 2,
          rowspan: 1,
          children: [
            {
              name: '增量回款',
              key: `${currentYear}-annualActual-IncrementalReturn`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '存量回款',
              key: `${currentYear}-annualActual-StoreReturn`,
              colspan: 1,
              rowspan: 1,
            },
          ],
        },
        {
          name: '年度测算数',
          key: `${currentYear}-annualCalculate`,
          colspan: 2,
          rowspan: 1,
          children: [
            {
              name: '增量回款',
              key: `${currentYear}-annualCalculate-IncrementalReturn`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '存量回款',
              key: `${currentYear}-annualCalculate-StoreReturn`,
              colspan: 1,
              rowspan: 1,
            },
          ],
        },
        {
          name: '年度调整数',
          key: `${currentYear}-annualAdjust`,
          colspan: 2,
          rowspan: 1,
          children: [
            {
              name: '增量回款',
              key: `${currentYear}-annualAdjust-IncrementalReturn`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '存量回款',
              key: `${currentYear}-annualAdjust-StoreReturn`,
              colspan: 1,
              rowspan: 1,
            },
          ],
        },
        {
          name: (
            <TableCell>
              <div>年度已签未回</div>
              <div>回款数</div>
            </TableCell>
          ),
          key: `${currentYear}-yearSignNotReturn`,
          colspan: 1,
          rowspan: 2,
        },
        {
          name: (
            <TableCell>
              <div>年初应退</div>
              <div>回款数</div>
            </TableCell>
          ),
          key: `${currentYear}-yearEarlyRefund`,
          colspan: 1,
          rowspan: 2,
        },
        {
          name: `${currentYear}年度回款合计`,
          key: `${currentYear}-annualTotal`,
          colspan: 4,
          rowspan: 1,
          children: [
            {
              name: '增量回款',
              key: `${currentYear}-annualTotal-IncrementalReturn`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '存量回款',
              key: `${currentYear}-annualTotal-StoreReturn`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '回款合计',
              key: `${currentYear}-annualTotal-ReturnTotal`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '年末应收账款',
              key: `${currentYear}-annualTotal-YearEndReceivable`,
              colspan: 1,
              rowspan: 1,
            },
          ],
        },
      ],
    },
  ];

  for (let i = 1; i <= 12; i += 1) {
    // 是否是当前时间之前
    const isCurrentTimeBefore = dayjs(`${currentYear}-${i}`).isBefore();
    // 是否是当前时间
    const isCurrentTime = dayjs(`${currentYear}-${i}`).isSame(dayjs().format('YYYY-MM'));
    // 当前月
    if (isCurrentTime) {
      columns.push({
        name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
        key: `${currentYear}${i}`,
        hidden: !_.includes(currentMonths, i.toString()),
        children: [
          {
            name: '期初应收账款',
            key: `${i}-field_6`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期签约',
            key: `${i}-monthSign`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期实际数',
            key: `${i}-monthlyActual`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyActualIncrementalReturn`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyActualStoreReturn`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '本期测算数',
            key: `${i}-monthlyCalculate`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyCalculateIncrementalReturn`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyCalculateStoreReturn`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '本期调整数',
            key: `${i}-monthlyAdjust`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyAdjustIncrementalReturn`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyAdjustStoreReturn`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: (
              <TableCell>
                <div>本期已签未回</div>
                <div>回款数</div>
              </TableCell>
            ),
            key: `${i}-monthSignNotReturn`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: (
              <TableCell>
                <div>本期期初应退</div>
                <div>回款数</div>
              </TableCell>
            ),
            key: `${i}-refundable`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期回款合计',
            key: `${i}-monthlyTotal`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyTotalIncrementalReturn`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyTotalStoreReturn`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '回款合计',
                key: `${i}-monthlyTotalReturnTotal`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '期末应收账款',
                key: `${i}-monthlyTotalMonthEndReceivable`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '回款率',
            key: `${i}-ReturnRate`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '累计签约回款率',
                key: `${currentYear}${i}-signReturnRate`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '年度综合回款率',
                key: `${currentYear}${i}-annualOverallReturnRate`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
        ],
      });
    }
    // 实际月
    if (!isCurrentTime && isCurrentTimeBefore) {
      columns.push({
        name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
        key: `${currentYear}${i}`,
        hidden: !_.includes(currentMonths, i.toString()),
        children: [
          {
            name: '期初应收账款',
            key: `${i}-field_6`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期签约',
            key: `${i}-monthSign`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期回款合计（实际数）',
            key: `${i}-monthlyTotal`,
            colspan: 3,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyTotalIncrementalReturn`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyTotalStoreReturn`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '回款合计',
                key: `${i}-monthlyTotalReturnTotal`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '回款率',
            key: `${i}-ReturnRate`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '累计签约回款率',
                key: `${i}-signReturnRate`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '年度综合回款率',
                key: `${i}-annualOverallReturnRate`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
        ],
      });
    }
    // 计划月
    if (!isCurrentTime && !isCurrentTimeBefore) {
      columns.push({
        name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
        key: `${currentYear}${i}`,
        hidden: !_.includes(currentMonths, i.toString()),
        children: [
          {
            name: '期初应收账款',
            key: `${i}-field_6`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期签约',
            key: `${i}-monthSign`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期测算数',
            key: `${i}-monthlyCalculate`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyCalculateIncrementalReturn`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyCalculateStoreReturn`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '本期调整数',
            key: `${i}-monthlyAdjust`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyAdjustIncrementalReturn`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyAdjustIncrementalReturn`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: (
              <TableCell>
                <div>本期已签未回</div>
                <div>回款数</div>
              </TableCell>
            ),
            key: `${i}-monthSignNotReturn`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期回款合计',
            key: `${i}-monthlyTotal`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyTotalIncrementalReturn`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyTotalStoreReturn`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '回款合计',
                key: `${i}-monthlyTotalReturnTotal`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '期末应收账款',
                key: `${i}-monthlyTotalMonthEndReceivable`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '回款率',
            key: `${i}-ReturnRate`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '累计签约回款率',
                key: `${i}-signReturnRate`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '年度综合回款率',
                key: `${i}-annualOverallReturnRate`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
        ],
      });
    }
  }
  titleTree[3].children = columns;
  return titleTree;
};
